 import axios from "axios";

 const cartModule = {
  state: {
    listItems:[],
    cartItems:JSON.parse(localStorage.getItem("cart")) || [],
    allSelected:JSON.parse(localStorage.getItem("allSelected"))||false
  },
  mutations: {
    getList(state,items){
      state.listItems = items;
    },
    addItemToCart(state,item){
      //判断购物车是否存在该商品
      var flag = false;
      state.cartItems.every((element)=>{
        if(element.id === item.id){
          flag = true;
          element.count++
        }
      })

      if(!flag){
        item.checked = false;
        item.count = 1;
        state.cartItems.push(item);
      }
      localStorage.setItem("cart",JSON.stringify(state.cartItems))
    },
    changeItemStatus(state,item){
      state.cartItems.forEach((element)=>{
        if(element.id  === item.id){
          element.checked = item.checked
        }
      })

      state.allSelected = state.cartItems.every((element)=>{
        return element.checked === true
      })

      localStorage.setItem("cart",JSON.stringify(state.cartItems))
      localStorage.setItem("allSelected",JSON.stringify(state.allSelected))
    },
    changeAllselect(state,boolean){
      state.allSelected = boolean;

      state.cartItems.forEach((element)=>{
        element.checked = boolean;
      })

      localStorage.setItem("cart",JSON.stringify(state.cartItems))
      localStorage.setItem("allSelected",JSON.stringify(state.allSelected))
    }
  },
  actions: {
    getList(context){
      axios.get("https://api.it120.cc/small4/shop/goods/list",{
      pageSize:100,
      page:1
      }).then((response)=>{
        window.console.log(response.data.data)
        context.commit("getList",response.data.data)
      }).catch((error)=>{
        window.console.log(error)
      })
    },
    addItemToCart(context,item){
      context.commit("addItemToCart",item)
    },
    changeItemStatus(context,item){
      context.commit("changeItemStatus",item)
    },
    changeAllselect(context,boolean){
      context.commit("changeAllselect",boolean)
    }
  },
  modules: {
    
  }
}

export default cartModule
